package unclassified.medium;

public class SumOfSubarrayRanges_5953 {

    public long subArrayRanges(int[] nums) {
        int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
        int res = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            max = min = nums[i];
            for (int j = i + 1; j < nums.length; j++) {
                max = Math.max(max, nums[j]);
                min = Math.min(min, nums[j]);
                res += max - min;
            }
        }
        return res;
    }

    public long subArrayRangesDP(int[] nums) {
        int n = nums.length;
        int[][] minArr = new int[n][n];
        int[][] maxArr = new int[n][n];
        for (int i = 0; i < nums.length; i++) {
            minArr[i][i] = nums[i];
            maxArr[i][i] = nums[i];
        }
        long res = 0;
        for (int i = 0; i < n; i++) {
            int max = maxArr[i][i], min = minArr[i][i];
            for (int j = i + 1; j < n; j++) {
                max = Math.max(nums[j], maxArr[i][j - 1]);
                min = Math.min(nums[j], minArr[i][j - 1]);
                maxArr[i][j] = max;
                minArr[i][j] = min;
                res += max - min;
            }
        }
        return res;
    }
}
